/*******************************************************************************
 * 文件名: PdfExport.java
 * 描    述: 导出PDF
 * 创建人: Dean Huang(hudi-112@163.com)
 * 日　期: 2018-01-11
 * 描　述: 文件描述
 * 版　本: 1.0
 *******************************************************************************/

package com.z1.core.data.export.pdf;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;

public class PdfMergeExport {

	private List<InputStream> inputs = null;
	
	public PdfMergeExport() {
	}
	public PdfMergeExport(List<InputStream> inputs) {
		this.inputs = inputs;
	}
	
	public List<InputStream> getInputs() {
		return inputs;
	}
	public void setInputs(List<InputStream> inputs) {
		this.inputs = inputs;
	}
	public void addInput(InputStream input) {
		if (null == inputs) {
			this.inputs = new ArrayList<InputStream>();
		}
		this.inputs.add(input);
	}
	public PdfMergeExport inputs(List<InputStream> inputs) {
		this.setInputs(inputs);
		return this;
	}
	public PdfMergeExport input(InputStream input) {
		this.addInput(input);
		return this;
	}
	
	public void export(OutputStream output) throws Exception {
		Document document = null;
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		try {
			document = new Document();
			PdfCopy copy = new PdfCopy(document, stream);
			document.open();
			document.newPage();
			for (InputStream input : inputs) {
				PdfReader pdfReader = new PdfReader(input);
				int n = pdfReader.getNumberOfPages();
				for (int j = 1; j <= n; j++) {
					PdfImportedPage page = copy.getImportedPage(pdfReader, j);
					copy.addPage(page);
				}
			}
			stream.flush();
		}
		catch (Throwable e) {
			e.printStackTrace();
		}
		finally {
			if (null != document) {
				document.close();
			}
		}
		stream.writeTo(output);
	}
	
}
